<template>
	<view class="content" >
		<u-loading-page  :loading="loading" bg-color="#e8e8e8" loading-text="loading..."></u-loading-page>
		<view class="host" style="padding-top: 15px;">
			<view class="host_body" v-for="(item,index) in hostList" :key="index">
				<view class="imageing" v-if="item.imgPath.split(',')[0]" @click="previewImage(index)">
					<img style="width: 345rpx;" mode="widthFix" :src="baseUrl+item.imgPath.split(',')[0]">
				</view>
				<view class="host_darkness">
					<u-row class="ty" justify="space-between">
						<u-col span="6" class="yui">
							<p class="yui">{{item.name}}</p>
						</u-col>
						<u-col span="6">
							<u-row justify="start">
								<u-col span="2">
								</u-col>
								<u-col span="4">
									<view class="animated like" hover-class="heartBeat">
										<image class="like" @click="toggleLike(index)"
											:src="item.isLiked ? '/static/icon/点赞.png' : '/static/icon/未点赞.png'"
											style="width: 40rpx; height: 40rpx;"></image>
									</view>
								</u-col>
								<u-col span="4">
									<view class="animated like" hover-class="heartBeat">
										<image class="like" @click="toggleCollection(index)"
											:src="item.isCollection ? '/static/icon/收藏2.png' : '/static/icon/收藏.png'"
											style="width: 40rpx; height: 40rpx;"></image>
									</view>
								</u-col>
							</u-row>
						</u-col>
					</u-row>
				</view>
			</view>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import request from '@/util/request'
	export default {
		onTabClick(index) {},
		onLoad() {
			// 获取设备信息
			const systemInfo = uni.getSystemInfoSync(); 
			// 提取设备号（唯一标识符） 
			let deviceId = systemInfo.deviceId; 
			this.deviceId = parseInt(deviceId);
			this.loading = true
			// this.selectColImgById() 
		},
		data() {
			return {
				deviceId: 0 ,
				baseUrl: 'https://absolutuniq.com:8088',
				loading: false,
				isLiked: false, // 是否已点赞
				isCollection: false, //是否已收藏
				status: 'loadmore',
				hostList: [],
			}
		},
		onShow() {
			this.selectColImgById() 
		},
		//无线下拉加载数据
		onReachBottom() {
			this.loading = true
		
			//定时器
			setTimeout(() => {
				// 这里放置你想要在等待5秒后执行的代码
				this.loading = false
			}, 1000);
			//数据触底以后，加载新的数据（就是加载新一页的数据）
		},
		computed: {
			divStyle() {
				return {
					color: 'green',
					border: '1px solid red'
				};
			},
		},
		methods: {
			showToast() {
				this.$refs.uToast.show({
					title: '加载数据',
					message: "加载数据",
					type: 'success',
				})
			},
			//点赞方法
			toggleLike(index) {
				// 切换点赞状态
				this.hostList[index].isLiked = !this.hostList[index].isLiked;
				// 准备发送到后端的数据
				const imgId = this.hostList[index].id; // 假设每个图像对象有一个 id
				const isLiked = this.hostList[index].isLiked;
				// 发送请求到后端
				request({
					url: '/favorites/favorites/toggleLike', // 假设这是处理点赞的后端 API 路径
					method: 'POST',
					data: {
						userId: this.deviceId, // 用户 ID
						imgManageId: imgId, // 图像 ID
						liked: isLiked // 当前的点赞状态
					}
				}).then(res => {
				
				}).catch(err => {
				
				});
			},
			// 收藏方法
			toggleCollection(index) {
				//切换收藏状态
				this.hostList[index].isCollection = !this.hostList[index].isCollection;
				// 准备发送到后端的数据
				const imgId = this.hostList[index].id; // 假设每个图像对象有一个 id
				const isCollection = this.hostList[index].isCollection;
				// 发送请求到后端
				request({
					url: '/favorites/favorites/toggleCollection', // 假设这是处理点赞的后端 API 路径
					method: 'POST',
					data: {
						userId: this.deviceId, // 用户 ID
						imgManageId: imgId, // 图像 ID
						col: isCollection // 当前的收藏状态
					}
				}).then(res => {
			
				}).catch(err => {
			
				});
			},
			selectColImgById() {
				 this.loading = true; // 开始加载状态
				
				    // 获取图片
				    const getImagesRequest = request({
				        url: '/favorites/favorites/selectColImgById?id=' + this.deviceId,
				        method: 'get'
				    });
				
				    // 获取用户点赞图片
				    const getLikesRequest = request({
				        url: '/favorites/favorites/getUserImageLike?id=' + this.deviceId,
				        method: 'get'
				    });
				
				    // 获取用户收藏图片
				    const getCollectionsRequest = request({
				        url: '/favorites/favorites/getUserImageCollection?id=' + this.deviceId,
				        method: 'get'
				    });
				
				    Promise.all([getImagesRequest, getLikesRequest, getCollectionsRequest])
				        .then(responses => {
				            const [imageResponse, likeResponse, collectionResponse] = responses;
							
							if(!imageResponse.data.data){
								this.hostList = []; // 清空hostList
								this.loading = false; // 加载结束
								uni.showToast({
								    title: '您还没有收藏过商品',
								    icon: 'none',
								    duration: 2000
								});
								return; // 如果都没有填写，退出方法
							}
				            // 处理图片数据
				            this.hostList = imageResponse.data.data.map(item => ({
				                ...item,
				                isCollection: false, // 初始状态为未收藏
				                isLiked: false, // 初始状态为未点赞
				                likeCount: 0 // 添加点赞数量字段
				            }));
				
				            // 处理点赞数据
				            const likedIds = new Set(likeResponse.data);
				            this.hostList = this.hostList.map(item => ({
				                ...item,
				                isLiked: likedIds.has(item.id) // 更新点赞状态
				            }));
				
				            // 处理收藏数据
				            const collectedIds = new Set(collectionResponse.data);
				            this.hostList = this.hostList.map(item => ({
				                ...item,
				                isCollection: collectedIds.has(item.id) // 更新收藏状态
				            }));
				
				            this.loading = false; // 加载结束
				        })
				        .catch(error => {

				            this.loading = false; // 加载结束
				        });
			},
			previewImage(index) {
				const imgUrls = this.hostList[index].imgPath.split(",");
				if (imgUrls.length > 0) {
					const newurls = imgUrls.map(item => {
						return item = this.baseUrl + item;
					});
					// 调用预览图片API
					uni.previewImage({
						current: 0, // 当前显示图片索引
						urls: newurls, // 需要预览的图片URL列表
					});
				}
			}
		}
	}
</script>
<style lang="scss">
	.like {
		color: #ffe833;
		filter: none;
		will-change: font-size;
		-webkit-animation: heart 1s cubic-bezier(0.17，8.89，8.32，1.49);
		animation: heart 1s cubic-bezier(0.17，0.89，8.32，1.49);
		width: 40rpx;
		height: 40rpx;

	}

	.noLike {
		width: 40rpx;
		height: 40rpx;

	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

	}

	.host {
		margin-top: 40rpx;
		margin: 0 auto;
		padding: 0 20rpx;
		column-count: 2;
		column-gap: 20rpx;

	}

	.host_body {
		width: 345rpx;
		border-radius: 20rpx;
		box-sizing: border-box;
		overflow: hidden;
		background-color: #fff;
		break-inside: avoid;
		/*避免在元素内部插入分页符*/
		box-sizing: border-box;
		/* 	margin-top: rpx; */
		margin-bottom: 20rpx;
		box-shadow: 0px 0px 28rpx 1rpx rgba(78, 101, 153, 0.14);
	}

	.imageing {
		width: auto;
		height: auto;
		position: relative;
		/* 使子元素可以相对于这个元素定位 */

	}


	.like-count img {
		margin-right: 5px;
		/* 图标与文本之间的间距 */
		width: 15px;
		/* 只设置宽度，高度自动调整 */
		height: 15px;
	}

	.types {
		width: 95%;
		margin: 0 auto;
		height: 70rpx;

	}

	.types_son {
		width: 80%;
		margin: 0 auto;
		height: 70rpx;
	}

	.imageing_img {
		width: 345rpx;
		height: auto;
	}

	.host_darkness {
		padding-left: 16rpx;
		font-size: 25rpx;
		margin-top: 15rpx;
		padding-bottom: 22rpx;

	}

	.darkness_silence {
		font-weight: 800;
		margin-top: 12rpx;
		font-size: 27rpx;
		margin-left: 10rpx;
	}

	.yui {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-top: 5px;
		font-size: 27rpx;
	}
</style>